package com.example.controller;

import com.example.common.ApiResponse;
import com.example.dto.LoginRequest;
import com.example.entity.User;
import com.example.security.UserDetailsImpl;
import com.example.service.AuthService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/auth")

public class AuthController {

    @Autowired
    private AuthService authService;
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        try {
            User user = authService.login(loginRequest.getEmail(), loginRequest.getPassword());
            if (user != null) {
                // 构造用户信息响应
                UserDetailsImpl userDetails =  UserDetailsImpl.build(user);
                ApiResponse<UserDetailsImpl> response = new ApiResponse<>(200, "Login successful", userDetails);
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.status(401).body(new ApiResponse<>(401, "Login failed", null));
            }

        } catch (BadCredentialsException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Login failed: " + e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + e.getMessage());
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        User newUser = authService.register(user);
        return ResponseEntity.ok(newUser);
    }
}
